"""
行政区域API路由
"""
from flask import Blueprint, jsonify
from app.models import import_models
from app import db

# 导入模型
models = import_models()
Region = models['Region']

region_bp = Blueprint('region', __name__, url_prefix='/api/regions')


@region_bp.route('/<int:parent_id>/children')
def get_children_regions(parent_id):
    """获取指定区域的下级行政区域"""
    try:
        parent_region = Region.query.get(parent_id)
        if not parent_region:
            return jsonify({'error': '父级区域不存在'}), 404
        
        children = Region.query.filter_by(parent_id=parent_id).all()
        result = []
        
        for child in children:
            result.append({
                'id': child.id,
                'name': child.name,
                'code': child.code,
                'level': child.level
            })
        
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@region_bp.route('/provinces')
def get_provinces():
    """获取所有省份"""
    try:
        provinces = Region.query.filter_by(level='省').all()
        result = []
        
        for province in provinces:
            result.append({
                'id': province.id,
                'name': province.name,
                'code': province.code
            })
        
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500